package cn.zifangsky.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.zifangsky.manager.UsrUserManager;
import cn.zifangsky.model.UsrUser;

@Controller
public class UserController {
	@Resource(name = "usrUserManager")
	private UsrUserManager userManager;

	/**
	 * 登录校验
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param request
	 * @param redirectAttributes
	 * @return 重定向到主页
	 */
	@RequestMapping("/user/user/check.html")
	public ModelAndView loginCheck(@RequestParam("username") String username, @RequestParam("password") String password,
			HttpServletRequest request, RedirectAttributes redirectAttributes) {
		HttpSession session = request.getSession();

		UsrUser result = userManager.login(username, password);
		if (result != null) {
			ModelAndView mAndView = null;
			// 登录之前地址
			String callback = (String) session.getAttribute("callback");
			session.removeAttribute("callback"); // 获取之后移除
			// 基本路径
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
			if (StringUtils.isNotBlank(callback)) {
				String[] urls = callback.split(basePath);
				if (urls.length == 2 && StringUtils.isNotBlank(urls[1])) {
					mAndView = new ModelAndView("redirect:" + urls[1]);
				} else
					mAndView = new ModelAndView("redirect:/main.html");
			} else
				mAndView = new ModelAndView("redirect:/main.html");

			session.setAttribute("user", result); // 登录成功之后加入session中
			redirectAttributes.addFlashAttribute("user", result);

			return mAndView;
		} else {
			redirectAttributes.addFlashAttribute("error", "登录失败，请重新登录");
			return new ModelAndView("redirect:/user/user/login.html");
		}

	}

	/**
	 * 注销登录
	 * 
	 * @param request
	 * @return 重定向回登录页面
	 */
	@RequestMapping("/user/user/logout.html")
	public ModelAndView logout(HttpServletRequest request) {
		userManager.logout(request.getSession());
		return new ModelAndView("redirect:/user/user/login.html");
	}
	
	@RequestMapping("/user/user/list.html")
	public ModelAndView list(){
		ModelAndView mAndView = new ModelAndView("/user/user/list");
		
		
		
		return mAndView;
	}

}
